<template>
  <view class="combination-container">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
    
    <!-- 错误提示 -->
    <view class="error-container" v-else-if="errorMsg">
      <view class="error-content">
        <text class="iconfont icon-error"></text>
        <text class="error-text">{{errorMsg}}</text>
        <button class="btn btn-primary" @click="retry">重试</button>
      </view>
    </view>
    
    <!-- 组合详情内容 -->
    <block v-else>
      <!-- 顶部组合信息 -->
      <view class="combination-header" :style="{ backgroundImage: `url(${combinationInfo.coverImage})` }">
        <!-- 顶部组合信息 -->
        <view class="header-mask">
          <view class="header-content">
            <view class="combination-title">{{combinationInfo.name}}</view>
            <view class="combination-desc">{{combinationInfo.description}}</view>
            
            <view class="combination-stats">
              <view class="stat-item">
                <text class="stat-value">{{formatNumber(combinationInfo.useCount)}}</text>
                <text class="stat-label">使用次数</text>
              </view>
              <view class="stat-item">
                <text class="stat-value">{{formatNumber(combinationInfo.likeCount)}}</text>
                <text class="stat-label">喜欢</text>
              </view>
              <view class="stat-item">
                <text class="stat-value">{{formatNumber(combinationInfo.favoriteCount)}}</text>
                <text class="stat-label">收藏</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 分享按钮 -->
        <button class="share-btn" open-type="share">
          <text class="iconfont icon-share"></text>
        </button>
      </view>
      
      <!-- 组合包含的风格 -->
      <view class="included-styles">
        <view class="section-title">包含风格</view>
        <scroll-view class="styles-scroll" scroll-x="true" show-scrollbar="false">
          <view 
            class="style-item" 
            v-for="(style, index) in styles" 
            :key="index"
            @click="goToStyle(style.id)"
          >
            <image class="style-image" :src="style.previewImage" mode="aspectFill"></image>
            <view class="style-name">{{style.name}}</view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 组合示例 -->
      <view class="combination-examples" v-if="examples.length > 0">
        <view class="section-title">组合效果示例</view>
        <scroll-view class="examples-scroll" scroll-x="true" show-scrollbar="false">
          <view class="example-item" v-for="(example, index) in examples" :key="index">
            <view class="example-compare">
              <image class="example-image" :src="example.originalImage" mode="aspectFill"></image>
              <image class="example-image" :src="example.resultImage" mode="aspectFill"></image>
            </view>
            <view class="example-label">
              <text>原图</text>
              <text>效果图</text>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 用户作品 -->
      <view class="user-works">
        <view class="section-title">用户作品</view>
        <view class="works-grid">
          <view 
            class="work-item" 
            v-for="(work, index) in userWorks" 
            :key="index"
            @click="goToDetail(work.id)"
          >
            <image class="work-image" :src="work.resultImage" mode="aspectFill"></image>
            <view class="work-info">
              <view class="work-user">
                <image class="user-avatar" :src="work.user && work.user.avatar ? work.user.avatar : '/static/images/default-avatar.png'" mode="aspectFill"></image>
                <text class="user-name">{{work.user && work.user.nickname ? work.user.nickname : '匿名用户'}}</text>
              </view>
              <view class="work-likes">
                <text class="iconfont icon-like"></text>
                <text class="likes-count">{{formatNumber(work.likeCount)}}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMoreWorks">
          <button class="btn btn-text" @click="loadMoreWorks" :disabled="loadingMore">
            {{loadingMore ? '加载中...' : '加载更多'}}
          </button>
        </view>
        
        <!-- 无数据提示 -->
        <view class="no-data" v-if="userWorks.length === 0 && !loadingMore">
          <text class="no-data-text">暂无相关作品</text>
        </view>
      </view>
      
      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <view class="bottom-actions">
          <button 
            class="btn btn-outline" 
            @click="toggleFavorite"
            :class="{'btn-favorite': isFavorite}"
          >
            <text class="iconfont" :class="isFavorite ? 'icon-star-filled' : 'icon-star'"></text>
            {{isFavorite ? '已收藏' : '收藏'}}
          </button>
          <button class="btn btn-primary btn-large" @click="useCombination">使用此组合</button>
        </view>
      </view>
    </block>
  </view>
</template>

<script>
import store from '@/store/index.js';
import { styleApi, feedApi } from '@/utils/api.js';

export default {
  data() {
    return {
      // 组合ID
      combinationId: null,
      
      // 组合信息
      combinationInfo: {
        id: 0,
        name: '',
        description: '',
        coverImage: '',
        previewImage: '',
        useCount: 0,
        likeCount: 0,
        favoriteCount: 0,
        creatorId: 0,
        creator: null,
        styleIds: []
      },
      
      // 包含的风格列表
      styles: [],
      
      // 组合示例
      examples: [],
      
      // 是否已收藏
      isFavorite: false,
      
      // 用户作品
      userWorks: [],
      
      // 分页信息
      page: 1,
      pageSize: 10,
      hasMoreWorks: true,
      loadingMore: false,
      
      // 加载状态
      loading: true,
      
      // 错误信息
      errorMsg: ''
    };
  },
  
  onLoad(options) {
    // 获取组合ID
    if (options && options.id) {
      // 将字符串ID转换为数字
      this.combinationId = parseInt(options.id, 10);
      
      // 加载组合详情
      this.loadCombinationDetail();
    } else {
      // 如果没有传入组合ID，则跳转到组合列表页
      uni.showToast({
        title: '组合ID不存在',
        icon: 'none',
        duration: 2000
      });
      
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/style/combinations'
        });
      }, 2000);
    }
  },
  
  methods: {
    /**
     * 加载组合详情
     */
    async loadCombinationDetail() {
      this.loading = true;
      
      try {
        // 调用API获取组合详情
        const response = await styleApi.getCombinationById(this.combinationId);
        
        // 检查返回的数据是否有效
        if (!response || response.code !== 200 || !response.data) {
          throw new Error(response?.msg || '组合数据不存在或无效');
        }
        
        this.combinationInfo = response.data;
        
        // 加载包含的风格
        if (this.combinationInfo.styleIds && this.combinationInfo.styleIds.length > 0) {
          this.loadIncludedStyles();
        }
        
        // 加载组合示例
        this.loadCombinationExamples();
        
        // 检查是否已收藏
        this.checkFavorite();
        
        // 加载用户作品
        this.loadUserWorks();
        
        // 添加到最近使用的组合
        if (store && store.addRecentCombination) {
          store.addRecentCombination({
            id: this.combinationInfo.id,
            name: this.combinationInfo.name,
            coverImage: this.combinationInfo.coverImage
          });
        }
      } catch (error) {
        console.error('加载组合详情失败', error);
        this.errorMsg = error.message || '加载组合详情失败，请稍后重试';
        
        uni.showToast({
          title: this.errorMsg,
          icon: 'none'
        });
        
        // 延迟返回或跳转到组合列表页
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/style/combinations'
          });
        }, 2000);
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 加载包含的风格
     */
    async loadIncludedStyles() {
      try {
        // 调用API获取组合包含的风格列表
        const response = await styleApi.getStylesByIds(this.combinationInfo.styleIds);
        
        if (response && response.code === 200 && response.data) {
          this.styles = response.data;
        } else {
          throw new Error(response?.msg || '获取风格列表失败');
        }
      } catch (error) {
        console.error('加载包含的风格失败', error);
        // 失败时使用空数组
        this.styles = [];
      }
    },
    
    /**
     * 加载组合示例
     */
    async loadCombinationExamples() {
      try {
        // 调用API获取组合示例
        const response = await styleApi.getCombinationExamples(this.combinationId);
        
        if (response && response.code === 200 && response.data) {
          this.examples = response.data;
        } else {
          throw new Error(response?.msg || '获取组合示例失败');
        }
      } catch (error) {
        console.error('加载组合示例失败', error);
        // 失败时使用空数组
        this.examples = [];
      }
    },
    
    /**
     * 检查是否已收藏
     */
    async checkFavorite() {
      try {
        // 调用API检查是否已收藏
        const response = await styleApi.checkFavoriteCombination(this.combinationId);
        
        if (response && response.code === 200) {
          this.isFavorite = response.data;
        }
      } catch (error) {
        console.error('检查收藏状态失败', error);
        // 失败时默认为未收藏
        this.isFavorite = false;
      }
    },
    
    /**
     * 切换收藏状态
     */
    async toggleFavorite() {
      try {
        // 乐观更新UI
        const originalState = this.isFavorite;
        this.isFavorite = !this.isFavorite;
        
        // 调用API切换收藏状态
        const response = await styleApi.toggleFavoriteCombination(this.combinationId, this.isFavorite);
        
        if (response && response.code === 200) {
          // 更新收藏计数
          if (this.isFavorite) {
            this.combinationInfo.favoriteCount++;
          } else {
            this.combinationInfo.favoriteCount = Math.max(0, this.combinationInfo.favoriteCount - 1);
          }
          
          uni.showToast({
            title: this.isFavorite ? '已收藏' : '已取消收藏',
            icon: 'none'
          });
        } else {
          // 恢复原始状态
          this.isFavorite = originalState;
          throw new Error(response?.msg || '操作失败');
        }
      } catch (error) {
        console.error('切换收藏状态失败', error);
        // 恢复原始状态
        this.isFavorite = !this.isFavorite;
        
        uni.showToast({
          title: '操作失败，请稍后重试',
          icon: 'none'
        });
      }
    },
    
    /**
     * 加载用户作品
     */
    async loadUserWorks() {
      if (this.loadingMore) return;
      
      this.loadingMore = true;
      
      try {
        // 调用API获取组合相关作品
        const params = {
          page: this.page,
          size: this.pageSize
        };
        
        const response = await styleApi.getCombinationWorks(this.combinationId, params);
        
        if (response && response.code === 200 && response.data) {
          const { list, total } = response.data;
          
          // 追加数据
          if (this.page === 1) {
            this.userWorks = list;
          } else {
            this.userWorks = [...this.userWorks, ...list];
          }
          
          // 更新分页信息
          this.hasMoreWorks = this.userWorks.length < total;
          
          if (this.hasMoreWorks) {
            this.page++;
          }
        } else {
          throw new Error(response?.msg || '获取用户作品失败');
        }
      } catch (error) {
        console.error('加载用户作品失败', error);
        uni.showToast({
          title: '加载用户作品失败',
          icon: 'none'
        });
      } finally {
        this.loadingMore = false;
      }
    },
    
    /**
     * 加载更多作品
     */
    loadMoreWorks() {
      if (!this.loadingMore && this.hasMoreWorks) {
        this.loadUserWorks();
      }
    },
    
    /**
     * 使用当前组合进行创作
     */
    useCombination() {
      // 将组合ID存储到本地，以便创作页面获取
      uni.setStorageSync('selectedCombinationId', this.combinationId);
      
      // 跳转到创作页面（使用switchTab而不是navigateTo）
      uni.switchTab({
        url: '/pages/create/create',
        success: () => {
          console.log('成功跳转到创作页面');
        },
        fail: (error) => {
          console.error('跳转失败', error);
          uni.showToast({
            title: '跳转失败，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    
    /**
     * 跳转到风格详情
     * @param {number} styleId - 风格ID
     */
    goToStyle(styleId) {
      uni.navigateTo({
        url: `/pages/style/style?id=${styleId}`
      });
    },
    
    /**
     * 跳转到作品详情
     * @param {number} artworkId - 作品ID
     */
    goToDetail(artworkId) {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${artworkId}`
      });
    },
    
    /**
     * 重试加载
     */
    retry() {
      this.errorMsg = '';
      this.loadCombinationDetail();
    },
    
    /**
     * 格式化数字显示
     * @param {number} num - 需要格式化的数字
     * @returns {string} 格式化后的数字字符串
     */
    formatNumber(num) {
      if (!num && num !== 0) return '0';
      
      if (num < 1000) {
        return num.toString();
      } else if (num < 10000) {
        return (num / 1000).toFixed(1) + 'k';
      } else {
        return (num / 10000).toFixed(1) + 'w';
      }
    }
  },
  
  /**
   * 分享设置
   */
  onShareAppMessage() {
    return {
      title: `AI风格重绘 - ${this.combinationInfo.name}`,
      path: `/pages/style/combination?id=${this.combinationId}`,
      imageUrl: this.combinationInfo.coverImage
    };
  },
  
  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: `AI风格重绘 - ${this.combinationInfo.name}`,
      query: `id=${this.combinationId}`,
      imageUrl: this.combinationInfo.coverImage
    };
  }
};
</script>

<style lang="scss">
@import '@/static/styles/global.scss';

.combination-container {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 120rpx;
}

.combination-header {
  height: 500rpx;
  background-size: cover;
  background-position: center;
  position: relative;
  
  .header-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 85%;
    background: linear-gradient(to bottom, rgba(0,0,0,0.3), rgba(0,0,0,0.7));
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    padding: 40rpx;
  }
  
  .header-content {
    color: #FFFFFF;
  }
  
  .combination-title {
    font-size: 48rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
  
  .combination-desc {
    font-size: 28rpx;
    margin-bottom: 20rpx;
    opacity: 0.9;
  }
  
  .combination-stats {
    display: flex;
    margin-bottom: 30rpx;
    
    .stat-item {
      margin-right: 40rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .stat-value {
        font-size: 32rpx;
        font-weight: bold;
      }
      
      .stat-label {
        font-size: 24rpx;
        opacity: 0.8;
      }
    }
  }
  
  .share-btn {
    position: absolute;
    top: 40rpx;
    right: 40rpx;
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    padding: 0;
    
    &::after {
      border: none;
    }
    
    .iconfont {
      font-size: 40rpx;
      color: #FFFFFF;
    }
  }
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: $text-color-primary;
  margin-bottom: 30rpx;
  padding: 0 30rpx;
}

.included-styles {
  padding: 40rpx 0;
  
  .styles-scroll {
    white-space: nowrap;
    padding: 0 30rpx;
  }
  
  .style-item {
    display: inline-block;
    width: 200rpx;
    margin-right: 20rpx;
    
    &:last-child {
      margin-right: 30rpx;
    }
  }
  
  .style-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: $border-radius-medium;
    box-shadow: $box-shadow-light;
  }
  
  .style-name {
    font-size: 24rpx;
    color: $text-color-primary;
    text-align: center;
    margin-top: 10rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.combination-examples {
  padding: 20rpx 0 40rpx;
  
  .examples-scroll {
    white-space: nowrap;
    padding: 0 30rpx;
  }
  
  .example-item {
    display: inline-block;
    width: 500rpx;
    margin-right: 20rpx;
    
    &:last-child {
      margin-right: 30rpx;
    }
  }
  
  .example-compare {
    display: flex;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  }
  
  .example-image {
    width: 250rpx;
    height: 300rpx;
  }
  
  .example-label {
    display: flex;
    justify-content: space-around;
    font-size: 24rpx;
    color: #666;
    margin-top: 10rpx;
  }
}

.user-works {
  padding: 20rpx 30rpx 40rpx;
  
  .works-grid {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10rpx;
  }
  
  .work-item {
    width: 50%;
    padding: 10rpx;
    box-sizing: border-box;
    margin-bottom: 20rpx;
  }
  
  .work-image {
    width: 100%;
    height: 340rpx;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  }
  
  .work-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 0;
  }
  
  .work-user {
    display: flex;
    align-items: center;
  }
  
  .user-avatar {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    margin-right: 10rpx;
  }
  
  .user-name {
    font-size: 24rpx;
    color: #666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200rpx;
  }
  
  .work-likes {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #666;
    
    .icon-like {
      margin-right: 6rpx;
    }
  }
  
  .load-more {
    text-align: center;
    margin-top: 20rpx;
  }
  
  .no-data {
    text-align: center;
    margin-top: 20rpx;
    color: #666;
  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
  box-sizing: border-box;
  
  .bottom-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .btn-outline {
      flex: 1;
      margin-right: 20rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 40rpx;
      border: 1px solid #FF69B4;
      color: #FF69B4;
      
      &.btn-favorite {
        background-color: rgba(255, 105, 180, 0.1);
      }
      
      .iconfont {
        margin-right: 10rpx;
      }
    }
    
    .btn-primary {
      flex: 2;
      height: 80rpx;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      font-weight: bold;
      background-color: #FF69B4;
      color: #fff;
    }
  }
}

.loading-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  
  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    animation: fadeIn 0.3s ease-in-out;
  }
  
  .loading-spinner {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    border: 10rpx solid #ccc;
    border-top-color: #FF69B4;
    animation: rotate 1s linear infinite;
  }
  
  .loading-text {
    font-size: 28rpx;
    color: #666;
    margin-top: 20rpx;
  }
}

.error-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  
  .error-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    animation: fadeIn 0.3s ease-in-out;
  }
  
  .icon-error {
    font-size: 80rpx;
    color: #666;
  }
  
  .error-text {
    font-size: 28rpx;
    color: #666;
    margin-top: 20rpx;
  }
  
  .btn-primary {
    margin-top: 40rpx;
    width: 200rpx;
    height: 80rpx;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: bold;
    background-color: #FF69B4;
    color: #fff;
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 添加过渡动画 */
.style-item, .example-item, .work-item {
  transition: transform 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
}
</style>
